<?php
defined('_XR_EXEC') or die();
/**
 * 逻辑处理类 在线充值
 */
class olpay_Model extends Model
{
	var $payinfo = array();
	function __construct(){
		$this->payinfo = factory::getcfg('payinfo',array(),'pay');
	}
	
	
	################################
	# 支付成功处理
	################################
	public function payfinish($orderid=0,$info=array()){ 
		$db = factory::getdbo();
		$db->begin();
		$rs_order = $db->loadassoc('select * from `#__webpaylog` where deleted=0 and ended=0 and orderid="'.$orderid.'" limit 0,1 ');
		if(!$rs_order){
			$this->setError('没有发现可操作的订单记录');
			return false;
		}
		/* 充值事务增加 */
		$trans_id = factory::module('trans')->add_byslug('webin99bill',$rs_order['user_id'],abs($rs_order['orderamount']/100),'在线充值，充值流水号：'.$orderid,'1','',false );
		if(!$trans_id){
			return false;
		}
		/* 更新webpaylog表 */
		if(!$db->update('webpaylog',array(
			'id'=>$rs_order['id'],
			'ordertime'=>$info['orderTime'],
			'paytype'=>$info['payType'],
			'dealid'=>$info['dealId'],
			'bankid'=>$info['bankId'],
			'bankdealid'=>$info['bankDealId'],
			'dealtime'=>$info['dealTime'],
			'payamount'=>$info['payAmount'],
			'fee'=>$info['fee'],
			'payresult'=>$info['payResult'],
			'errcode'=>$info['errCode'],
			'signmsg'=>$info['signMsg'],
			'callbackip'=>func::get_server_ip(),
			'accountflag'=>'1',
			'responseinfo'=>json_encode($_REQUEST),
			'modified'=>'now()',
			'ended'=>'1',
			'trans_id'=>$trans_id
		))){
			return false;
		}	
		$db->commit();
		return true;
	}
	
	
	
	
	
	
	
	
	
	
	# 得到当前在线充值的类型描述，暂支持 1 快钱的人民币 2 快钱的神州行充值卡
	public function paytype_desc($key){
		if(isset($this->payinfo[$key])) return $this->payinfo[$key]['pay_desc'];
		return '';
	}
	################################################
	# 获取支付表单
	################################################
	public function webpayform($user_id=0,$paytype='rmb',$amount=0){
		# 验证
		if(!$this->verify_paytype($paytype) || !$this->verify_amount($paytype,$amount)){
			return false;
		}
		$user_id = intval($user_id);
		$amount = intval( floatval($amount) * 100 );
		# 验证用户是否存在
		$db = factory::getdbo();
		$rs_user = $db->loadassoc('select * from `#__user` where id="'.$user_id.'" and usertype=2 and deleted=0 ');
		if(!$rs_user){
			$this->setError('充值账户不存在');
			return false;
		}
		/* 根据类型得到最终的支付表单 */
		switch($paytype){
			case "rmb":
				return $this->entpay_rmb($user_id,$amount);
				break;
			default:
				$this->setError('充值类型不存在');
				return false;
				break;		
		}
		return false;
	}
	/* 企业支付 快钱rmb */
	public function entpay_rmb($user_id,$amount){
		$db = factory::getDBO();
		$db->begin();
		$rs_user = $db->loadassoc('select * from `#__user` where id="'.$user_id.'" and usertype=2 and deleted=0 ');
		$orderid = date('Ymd').rand(1000000,9999999);
		//$orderid = date('YmdHis').$user_id.rand(100,999);
		// 新建支付记录
		$webpaylog_id = $db->insert('webpaylog',array(
			'paytypekey'=>'rmb',
			'user_id'=>$user_id,
			'orderid'=>$orderid,
			'orderamount'=>$amount,
			'clientip'=>func::get_client_ip(),
			'created'=>'now()',
			'modified'=>'now()',
			'ended'=>'0',
			'trans_id'=>'0',
			'deleted'=>'0'
		));
		if(!$webpaylog_id){
			$this->setError('支付记录创建失败');
			return false; 
		}
		$curpay = $this->payinfo['rmb'];
		$strnow = date('YmdHis');
		//debug::show($webpaylog_id,$curpay,$strnow);
		//生成加密签名串
		$form_val = array();
		$signMsgVal = '';
		$signMsgVal=$this->appendParam($signMsgVal,"inputCharset",$curpay['inputCharset']);
		$form_val['inputCharset'] = $curpay['inputCharset'];
		$signMsgVal=$this->appendParam($signMsgVal,"bgUrl",$curpay['bgUrl']);
		$form_val['bgUrl'] = $curpay['bgUrl'];
		$signMsgVal=$this->appendParam($signMsgVal,"pageUrl",$curpay['pageUrl']);
		$form_val['pageUrl'] = $curpay['pageUrl'];
		$signMsgVal=$this->appendParam($signMsgVal,"version",$curpay['version']);
		$form_val['version'] = $curpay['version'];
		$signMsgVal=$this->appendParam($signMsgVal,"language",$curpay['language']);
		$form_val['language'] = $curpay['language'];
		$signMsgVal=$this->appendParam($signMsgVal,"signType",$curpay['signType']);
		$form_val['signType'] = $curpay['signType'];
		$signMsgVal=$this->appendParam($signMsgVal,"merchantAcctId", $curpay['merchantAcctId']);
		$form_val['merchantAcctId'] = $curpay['merchantAcctId'];
		$signMsgVal=$this->appendParam($signMsgVal,"payerName",$rs_user['name']);
		$form_val['payerName'] = $rs_user['name'];
		if($rs_user['phone'] != ''){
			$curpay['payerContactType'] = '2';
			$curpay['payerContact'] = $rs_user['phone'];
		}else{
			$curpay['payerContactType'] = '1';
			$curpay['payerContact'] = $rs_user['email'];
		}
		$signMsgVal=$this->appendParam($signMsgVal,"payerContactType",$curpay['payerContactType']);
		$form_val['payerContactType'] = $curpay['payerContactType'];
		$signMsgVal=$this->appendParam($signMsgVal,"payerContact",$curpay['payerContact']);
		$form_val['payerContact'] = $curpay['payerContact'];
		$signMsgVal=$this->appendParam($signMsgVal,"orderId",$orderid);
		$form_val['orderId'] = $orderid;
		$signMsgVal=$this->appendParam($signMsgVal,"orderAmount",$amount);
		$form_val['orderAmount'] = $amount;
		$signMsgVal=$this->appendParam($signMsgVal,"orderTime",$strnow);
		$form_val['orderTime'] = $strnow;
		$signMsgVal=$this->appendParam($signMsgVal,"productName",$curpay['productName']);
		$form_val['productName'] = $curpay['productName'];
		$signMsgVal=$this->appendParam($signMsgVal,"productNum",$curpay['productNum']);
		$form_val['productNum'] = $curpay['productNum'];
		$signMsgVal=$this->appendParam($signMsgVal,"productId",$curpay['productId']);
		$form_val['productId'] = $curpay['productId'];
		$signMsgVal=$this->appendParam($signMsgVal,"productDesc",$curpay['productDesc']);
		$form_val['productDesc'] = $curpay['productDesc'];
		$signMsgVal=$this->appendParam($signMsgVal,"ext1",$curpay['ext1']);
		$form_val['ext1'] = $curpay['ext1'];
		$signMsgVal=$this->appendParam($signMsgVal,"ext2",$curpay['ext2']);
		$form_val['ext2'] = $curpay['ext2'];
		$signMsgVal=$this->appendParam($signMsgVal,"payType",$curpay['payType']);	
		$form_val['payType'] = $curpay['payType'];
		$signMsgVal=$this->appendParam($signMsgVal,"bankId",$curpay['bankId']);	
		$form_val['bankId'] = $curpay['bankId'];
		$signMsgVal=$this->appendParam($signMsgVal,"redoFlag",$curpay['redoFlag']);
		$form_val['redoFlag'] = $curpay['redoFlag'];
		$signMsgVal=$this->appendParam($signMsgVal,"pid",$curpay['pid']);
		$form_val['pid'] = $curpay['pid'];
		//debug::show($this->getPrivatePath().DS.$curpay['rsa_my_private']);
		/////////////  RSA 签名计算 ///////// 开始 //
		$fp = fopen($this->getPrivatePath().$curpay['rsa_my_private'], "r");
		$priv_key = fread($fp, 8192);
		fclose($fp);
		$pkeyid = openssl_get_privatekey($priv_key);
		// compute signature
		openssl_sign($signMsgVal, $signMsg, $pkeyid,OPENSSL_ALGO_SHA1);
		// free the key from memory
		openssl_free_key($pkeyid);
		$signMsg = base64_encode($signMsg).'';
		/////////////  RSA 签名计算 ///////// 结束 //
		$form_val['signMsg'] = $signMsg; 
		$db->commit();
		return array(
			'action'=>$curpay['submiturl'],
			'method'=>$curpay['post_method'],
			'hiddens'=>$form_val
		);
	}
	
	//获取商户私钥地址主目录
	public function getPrivatePath(){
		return XR_APP_APPLICATION.'cermisc'.DS;
	}
	//获取快钱公钥地址主目录
	public function getPublicPath(){
		return XR_APP_APPLICATION.'cermisc'.DS;
	}
	
	//功能函数。将变量值不为空的参数组成字符串
	public function appendParam($returnStr,$paramId,$paramValue){
		if($returnStr!=""){
			if($paramValue!=""){
				$returnStr.="&".$paramId."=".$paramValue;
			} 
		}else{ 
			if($paramValue!=""){
				$returnStr=$paramId."=".$paramValue;
			}
		} 
		return $returnStr;
	}
	

	/* 充值类型验证 */
	public function verify_paytype($key){
		if(isset($this->payinfo[$key])){
			return true;
		}else{
			$this->setError('充值类型不存在');
			return false;
		}
	}
	/* 金额大小验证 */
	public function verify_amount($key,$fee){
		$cur = $this->payinfo[$key];
		if($fee < $cur['paymin'] || $fee > $cur['paymax']){
			$this->setError('充值金额超出了有效范围');
			return false;
		}
		return true;
	}
	
	
}

?>